// https://www.cnblogs.com/tangyifeng/p/7364727.html
var menuArry = [
/*    {id: 2, name: "用户列表", icon: 'fa fa-user-o', url: '#', pid: 1, path: '0-1-'},
    {id: 3, name: "用户账户", icon: 'fa fa-user-o', url: '/pjax/test', pid: 1, path: '0-1-'},
    {id: 4, name: "用户数据", icon: 'fa fa-user-o', url: 'www.baidu.com', pid: 2, path: '0-1-2-'},
    {id: 5, name: "今日委托单", icon: 'fa fa-user-o', url: '#', pid: 0, path: '0-'},
    {id: 6, name: "今日成交单", icon: 'fa fa-user-o', url: '#', pid: 5, path: '0-5-'},
    {id: 1, name: "交易系统管理", icon: 'fa fa-user-o', url: '#', pid: 0, path: '0-'},
    {id: 7, name: "历史委托单", icon: 'fa fa-user-o', url: 'www.baidu.com', pid: 6, path: '0-5-6-'},
    {id: 8, name: "历史成交单", icon: 'fa fa-user-o', url: 'www.baidu.com', pid: 6, path: '0-5-6-'},*/
];


var menus = '';
$(function () {
    $.ajax({
        url:'/admin/role/menu/list',
        type:'post',
        isHook:true,
        success:function (res) {
            menuArry = res.data;
            console.log(menuArry);
            GetData(0, menuArry)
            $('.menu').html(menus)
        }
    })
})

function GetData(id, arry) {
    var childArry = getParentArry(id, arry);
    if (childArry.length > 0) {
        menus += '<ul>';
        for (var i in childArry) {
            var hasChild = hasChildren(childArry[i].id, arry);
            var level = getLevel(childArry[i].menuPath);
            menus += '<li class=level-' + level + '>';
            if (hasChild) {
                menus += '<div class=item-' + level + ' onclick="toggle(this)">';
            } else {
                menus += '<div class=item-' + level + '>';
            }
            menus += '<i class="' + childArry[i].menuIcon + '">' + '</i>';
            if (childArry[i].menuUrl=='#'){
                menus += '<a href=' + childArry[i].menuUrl + '>' + childArry[i].menuName + '</a>';
            }else{
                menus += '<a data-pjax type="menu" href=' + childArry[i].menuUrl + '>' + childArry[i].menuName + '</a>';
            }


            if (hasChild) {
                menus += '<i class="fa fa-angle-down fr c">' + '</i>';
            }
            menus += '</div>';
            GetData(childArry[i].id, arry);
            menus += '</li>';
        }
        menus += '</ul>';

    }
}

function getParentArry(id, arry) {
    var newArry = new Array();
    for (var i in arry) {
        if (arry[i].menuPid == id)
            newArry.push(arry[i]);
    }
    return newArry;
}

function getLevel(menuPath) {
    return menuPath.split('-').length - 1;
}

function hasChildren(id, arry) {
    return getParentArry(id, arry).length > 0;
}

function toggle(_this) {
    var brother = $(_this).siblings();
    var brotherHeight = $(brother).height();
    if (brotherHeight == 0) {
        $(brother).children().css('display', 'block')
    } else {
        $(brother).children().css('display', 'none')
    }
}
